import { NextRequest, NextResponse } from 'next/server';
import { successResponse, errorResponse } from '@/lib/response';
import { corsMiddleware } from '@/lib/middleware/cors';
import { withLogging } from './logging';
import { logger } from '../logger';

export type AppRouteHandler<T = any> = (
  request: NextRequest,
  context?: { params: any }
) => Promise<T> | T;

export type AppRouteHandlerWithParams<T = any> = (
  request: NextRequest,
  context: { params: any }
) => Promise<T> | T;

// 支持自定义上下文的处理函数类型
export type AppRouteHandlerWithContext<T = any, C = any> = (
  request: NextRequest,
  context: C,
  routeContext?: { params: any }
) => Promise<T> | T;

// 中间件包装器
export const withMiddleware = <T = any>(
  handler: AppRouteHandler<T> | AppRouteHandlerWithParams<T>,
  options?: {
    beforeCallback?: ((req: NextRequest, context?: any) => Promise<any>)[];
  }
) => {
  // 使用日志记录中间件包装处理器
  const loggedHandler = withLogging(handler);
  
  return async function wrappedHandler(
    request: NextRequest, 
    context?: { params: any }
  ): Promise<NextResponse> {
    const start = Date.now();
    const url = request.nextUrl.pathname + request.nextUrl.search;
    
    // 记录请求开始
    logger.info(`API Request started: ${request.method} ${url}`, {
      method: request.method,
      url,
      userAgent: request.headers.get('user-agent'),
      ip: request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip')
    });

    try {
      // 执行前置中间件
      const middlewares = [
        corsMiddleware,
        ...(options?.beforeCallback || [])
      ];

      for (const middleware of middlewares) {
        await middleware(request, context || { params: {} });
      }

      // 执行主处理函数（已包装日志记录）
      const result = await loggedHandler(request);

      // 计算请求耗时
      const duration = Date.now() - start;
      
      // 记录请求完成
      if (duration < 2000) {
        logger.info(`API Request completed: ${request.method} ${url}`, {
          method: request.method,
          url,
          duration,
          status: 'success'
        });
      } else {
        logger.warn(`API Request slow: ${request.method} ${url}`, {
          method: request.method,
          url,
          duration,
          status: 'slow'
        });
      }

      // 如果返回的是NextResponse，直接返回
      if (result instanceof NextResponse) {
        return result;
      }

      // 如果返回的是原生Response，转换为NextResponse后返回，避免类型不匹配
      if (result instanceof Response) {
        const res = result as Response;
        const body = await res.arrayBuffer();
        const nextRes = new NextResponse(body, {
          status: res.status,
          statusText: res.statusText,
          headers: res.headers
        });
        return nextRes;
      }
    
      // 否则包装为成功响应
      return successResponse(result);

    } catch (error: any) {
      console.log(error,'error')
      console.error(`[API] Request error: ${request.method} ${url}`, error);
    
      // 根据错误消息判断错误类型
      const errorMessage = typeof error === 'string' ? error : (error?.message || error?.toString() || '服务器内部错误');
      let errorCode = 500;

      // 认证相关错误
      if (errorMessage.includes('认证失败') ||
          errorMessage.includes('缺少认证token') ||
          errorMessage.includes('token无效') ||
          errorMessage.includes('token已过期')||
          errorMessage.includes('无效的管理员token')) {
        errorCode = 401;
      }
      // 权限相关错误
      else if (errorMessage.includes('权限不足') ||
               errorMessage.includes('无权限')) {
        errorCode = 403;
      }
      // 参数错误
      else if (errorMessage.includes('为必填项') ||
               errorMessage.includes('格式不正确') ||
               errorMessage.includes('参数错误')) {
        errorCode = 400;
      }
      // 资源不存在
      else if (errorMessage.includes('不存在')) {
        errorCode = 404;
      }
      // 如果有自定义错误码，使用自定义的
      else if (error.code || error.status) {
        errorCode = error.code || error.status;
      }

      return errorResponse(errorMessage, errorCode);
    }
  };
};

// 简化的导出，兼容之前的使用方式
export const NextAPI = withMiddleware;

// 组合客户端认证和标准中间件
export const withClientMiddleware = <T = any>(
  handler: AppRouteHandler<T> | AppRouteHandlerWithParams<T>
) => {
  return withMiddleware(handler, {
    beforeCallback: [
      // 这里可以添加客户端认证逻辑
      async (req: NextRequest) => {
        // 客户端认证逻辑会在这里执行
        // 认证失败会抛出错误，被withMiddleware捕获
      }
    ]
  });
};

// 组合管理员认证和标准中间件
export const withAdminMiddleware = <T = any>(
  handler: AppRouteHandler<T> | AppRouteHandlerWithParams<T>,
  options?: { requiredRole?: 'admin' | 'super_admin' }
) => {
  return withMiddleware(handler, {
    beforeCallback: [
      // 这里可以添加管理员认证逻辑
      async (req: NextRequest) => {
        // 管理员认证逻辑会在这里执行
      }
    ]
  });
};